import { defineStore } from 'pinia'
import getUserLikesRequest from '@/api/Desktop/articles/getUserLikes.js'
import userAddLikeRequest from '@/api/Desktop/articles/userAddLike.js'
import userCanelLikeRequest from '@/api/Desktop/articles/userCanelLike.js'
import userDownLoadRequest from '@/api/Desktop/articles/userDownLoad.js'
import CardListStore from '../CardList/index.js'
import  showDialog  from '@/libs/dialog/showDialog.js'
const useCardListStore = CardListStore()
const userStore = defineStore('userStore', {
  state: () => {
    return {
      userInfo: {
        user_id: 'admin',
        avatar: '',
        username: '',
        email: ''
      },
      //目前点赞的文章列表
      likes: [],
    }
  },
  actions: {
    //获取用户点赞文章
    async getUserLikes() {
      const result = await getUserLikesRequest(this.userInfo.user_id)
      this.likes = result.likedArticles
    },
    //处理用户点赞
    async userAddLike(article_id) {
    //拿到文章id 同时去找到对应的文章保存当前文章点赞次数
    const hasLiked = this.likes.includes(article_id)
    if(!hasLiked) {
      const article = useCardListStore.photoData.find(item => item.id === article_id)
      const result = await userAddLikeRequest(article_id,this.userInfo.user_id)
      if(result.data.code === 200) {
        showDialog({
          title:`用户:${this.userInfo.user_id}你已点赞成功`,
          width: '500px',
          height: '300px',
          showOk:true
        })
        this.getUserLikes()
        //修改对应的like数量
        article.like = result.data.likeCount
      }
         else{
          showDialog({
            title:`点赞失败请重试`,
            width: '500px',
            height: '300px',
            showOk:true
          })
      }  
    }
    },
    //处理用户取消点赞
    async userCancelLike(article_id) {
      //判断用户点赞列表中是否有目前文章id如果有则进行删除
      const hasLiked = this.likes.includes(article_id)
      if(hasLiked) {
        const result = await userCanelLikeRequest(article_id,this.userInfo.user_id)
         const article = useCardListStore.photoData.find(item => item.id === article_id)
         if(result.code === 200) {
          this.getUserLikes()
            showDialog({
            title:`取消点赞成功`,
            width: '500px',
            height: '300px',
            showOk:true
          })
          article.like = result.likeCount
         } else{
           return false
         }
      }
    },
    //处理用户用户下载文章
    async userDownLoad(article_title,user_id,category_id) {
      const result = await userDownLoadRequest(article_title,user_id,category_id)
      if(result.code === 200) {
        //创建下载标签
        const a = document.createElement('a')
        a.href = result.data.Url
        a.download = article_title
        a.click()
      }
    }
  }
})
export default userStore
